import base64
import json
import pickle
from pprint import pprint

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponseNotFound
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import GoodsCateogory, Goods
from apps.index.utlis import get_category, get_category_goods, get_goods, data_get_goods
from utils import constants
from utils.response_code import RETCODE


class ListView(View):
    def get(self, request, category_id, page_num):
        # print(page_num)
        # 获取商品分类
        categories = {}
        goods_dict = {}

        category_dict = get_category()

        # pprint(category_dict)
        # print("---------:", category_id, type(category_id))
        # 判断分类id是1级还是2级
        if GoodsCateogory.objects.filter(id=category_id, parent_category=None):
            categories = category_dict[int(category_id)]  # 从所有分类数据中取出属于当前页面的分类，按照分类id取
            # 获取商品数据
            goods_dict = get_category_goods(category_id)
            pprint(goods_dict)
        else:
            parent = GoodsCateogory.objects.get(id=category_id).parent_category  # 取出当前分类的父类对象
            categories = category_dict[int(parent.id)]  # 获取所有分类

            # 获取商品数据
            goods_dict = get_category_goods(category_id)
            # pprint(goods_dict)

        # 分页
        # 查询分类的书籍
        # 判断分类id是1级还是2级
        goods = get_goods(category_id)
        # 创建分页器：每页N条记录
        paginator = Paginator(goods, 8)
        # 获取每页商品数据
        try:
            page_books = paginator.page(page_num)
            # print(page_books,'page_books,1111111111')
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages
        # for item in page_books:
        # print(item.name)

        context = {
            "categories": categories,
            # 当前分类的字典
            "category_dict": category_dict,  # 所有分类的字典
            "goods_dict": goods_dict,
            'category_page_id': int(category_id),
            'page_skus': page_books,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
        }
        # print(categories, '这是categories')

        return render(request, "Sculpture_cp.html", context)


class DetailView(View):
    def get(self, request, good_id):
        good_detial = data_get_goods(good_id)
        # print(data_get_goods)
        context = {
            'good_detial': good_detial
        }
        # print(good_detial)
        return render(request, 'ShopDetails.html', context)

